import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Tag, 
  Input, 
  Select, 
  Row, 
  Col,
  Card,
  Spin,
  message
} from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import api from '../services/api';

const { Search } = Input;
const { Option } = Select;

const CaseLibraryPage = () => {
  const [cases, setCases] = useState([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    category: null,
    approved: null
  });
  const history = useHistory();

  // 获取案例列表
  const fetchCases = async () => {
    setLoading(true);
    try {
      const params = {};
      if (filters.category) params.category = filters.category;
      if (filters.approved) params.approved = filters.approved;
      
      const response = await api.get('/cases', { params });
      setCases(response.data);
    } catch (error) {
      console.error('获取案例列表失败:', error);
      message.error('获取案例列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCases();
  }, [filters]);

  const handleSearch = async (value) => {
    if (value) {
      setLoading(true);
      try {
        const response = await api.get('/cases', { params: { search: value } });
        setCases(response.data);
      } catch (error) {
        console.error('搜索案例失败:', error);
        message.error('搜索案例失败');
      } finally {
        setLoading(false);
      }
    } else {
      fetchCases();
    }
  };

  const handleCategoryChange = (value) => {
    setFilters({ ...filters, category: value });
  };

  const handleStatusChange = (value) => {
    setFilters({ ...filters, approved: value });
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <a onClick={() => history.push(`/cases/${record.id}`)}>{text}</a>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category'
    },
    {
      title: '创建者',
      dataIndex: 'created_by',
      key: 'created_by'
    },
    {
      title: '状态',
      dataIndex: 'approved',
      key: 'approved',
      render: (approved) => (
        <Tag color={approved ? 'green' : 'orange'}>
          {approved ? '已审核' : '待审核'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (created_at) => new Date(created_at).toLocaleString()
    }
  ];

  return (
    <div>
      <h2>案例库</h2>
      
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Search 
              placeholder="搜索案例" 
              allowClear 
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
            />
          </Col>
          <Col span={6}>
            <Select 
              placeholder="分类" 
              style={{ width: '100%' }} 
              allowClear
              onChange={handleCategoryChange}
            >
              <Option value="hardware">硬件</Option>
              <Option value="software">软件</Option>
              <Option value="firmware">固件</Option>
              <Option value="network">网络</Option>
            </Select>
          </Col>
          <Col span={6}>
            <Select 
              placeholder="状态" 
              style={{ width: '100%' }} 
              allowClear
              onChange={handleStatusChange}
            >
              <Option value="true">已审核</Option>
              <Option value="false">待审核</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={() => history.push('/cases/create')}
              block
            >
              新建案例
            </Button>
          </Col>
        </Row>
      </Card>
      
      {loading ? (
        <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />
      ) : (
        <Table
          columns={columns}
          dataSource={cases}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true
          }}
        />
      )}
    </div>
  );
};

export default CaseLibraryPage;